<script setup lang="ts">
import friendsItem from "../components/friendsItem.vue";
import {} from "../api/connect";
import { getFriendsApi } from "../api/friendsShip";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import {
  getChatsRoomGroupListApi,
  createOneToOneChatsRoomApi,
} from "../api/chatsRoom";

const router = useRouter();

const friendsList = ref<IUser[]>();
const chatsRoomList = ref<IChats[]>();
const getConnentList = async () => {
  const res = await getFriendsApi();
  const res2 = await getChatsRoomGroupListApi();
  chatsRoomList.value = res2.data;
  friendsList.value = res.data;
};

const showPopover = ref(false);

// 通过 actions 属性来定义菜单选项
const actions = [
  { text: "加入群聊", value: "1" },
  { text: "添加好友", value: "2" },
];
const onSelect = (actions: { text: string; value: string }) => {
  if (actions.value === "1") {
    router.push({ name: "search", params: { type: 1 } });
  }
  if (actions.value === "2") {
    router.push({ name: "search", params: { type: 0 } });
  }
};

// 创建单聊
const createOneToOneChatsRoom = async (id: number, name: string) => {
  await createOneToOneChatsRoomApi(id);
  router.push({
    name: "chatsDetail",
    params: { roomId: id, roomName: name, type: 0 },
  });
};

onMounted(() => {
  getConnentList();
});
</script>

<template>
  <div class="connect">
    <VanNavBar title="通讯录">
      <template #right>
        <van-popover
          placement="left-start"
          v-model:show="showPopover"
          :actions="actions"
          @select="onSelect"
        >
          <template #reference>
            <van-icon name="plus" size="18" />
          </template>
        </van-popover>
      </template>
    </VanNavBar>
    <div class="connect__group">
      <div class="connect__title">我的好友</div>
      <friendsItem
        v-for="item in friendsList"
        :data="{ name: item.username, id: item.id }"
        @click="createOneToOneChatsRoom(item.id, item.username)"
      ></friendsItem>
    </div>
    <div class="connect__user">
      <div class="connect__title">我加入的群里</div>
      <friendsItem
        @click="
          router.push({
            name: 'chatsDetail',
            params: {
              roomId: item.chatRoomId,
              roomName: item.chatRoom.name,
              type: '1',
            },
          })
        "
        v-for="item in chatsRoomList"
        :data="{ id: item.chatRoomId, name: item.chatRoom.name }"
      ></friendsItem>
    </div>
  </div>
</template>
